package ferp.android.dialogs;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import ferp.android.GUI;
import ferp.android.R;

/**
 * User: igorgok
 * Date: 10/28/12 1:41 PM
 */
public class ReportGameDialog extends Dialog
{
  public interface Listener
  {
    void onSendClick(String email, String description);
  }

  public static String getEmail(Context context, String def)
  {
    return context.getSharedPreferences(Key.GAME_REPORT, Context.MODE_PRIVATE).getString(Key.EMAIL, def);
  }

  public ReportGameDialog(final Context context, Listener listener)
  {
    super(context, R.layout.dialog_report_game, R.string.dialog_report_game_title);

    this.listener = listener;

    setCancelable(true);

    ((TextView)findViewById(R.id.dlg_report_game_label_email)).setTypeface(GUI.Font.BOLD);
    ((TextView)findViewById(R.id.dlg_report_game_label_description)).setTypeface(GUI.Font.BOLD);

    email = (EditText)findViewById(R.id.dlg_report_game_edit_email);
    email.setTypeface(GUI.Font.NORMAL);

    final SharedPreferences prefs = context.getSharedPreferences(Key.GAME_REPORT, Context.MODE_PRIVATE);
    email.setText(prefs.getString(Key.EMAIL, ""));

    description = (EditText)findViewById(R.id.dlg_report_game_edit_description);
    description.setTypeface(GUI.Font.NORMAL);

    Button send = resolveButton(R.id.dlg_element_footer_button, R.string.dialog_report_game_send_report);

    send.setOnClickListener(new View.OnClickListener()
    {
      public void onClick(View view)
      {
        String em = email.getText().toString().trim();

        if (em.length() > MAX_EMAIL_LENGTH)
          GUI.toast(context, String.format(context.getResources().getString(R.string.dialog_report_game_error_email_too_long), MAX_EMAIL_LENGTH));
        else
          if (!Patterns.EMAIL_ADDRESS.matcher(em).matches())
            GUI.toast(context, R.string.dialog_report_game_error_email_invalid);
          else
          {
            ReportGameDialog.this.listener.onSendClick(em, description.getText().toString().trim());

            SharedPreferences.Editor editor = prefs.edit();
            editor.putString(Key.EMAIL, email.getText().toString());
            editor.commit();

            dismiss();
          }
      }
    });
  }

  public void reset()
  {
    email.setText(getEmail(getContext(), ""));
    description.getText().clear();
  }

  // preference keys
  private static final class Key
  {
    private static final String GAME_REPORT = "game_report";
    private static final String EMAIL       = "email";
  }

  private static final int MAX_EMAIL_LENGTH = 64;

  private final Listener listener;
  private final EditText email;
  private final EditText description;
}
